package com.stars.pao.captcha.controller;


import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpSession;
import java.util.Date;

@Slf4j
@RequestMapping("/admin")
@RestController
public class KaptchaController {
    private static final String KAPTCHA_SESSION_KEY = "KAPTCHA_SESSION_KEY";
    private static final String KAPTCHA_SESSION_DATE = "KAPTCHA_SESSION_DATE";
    private static final long TIME_OUT = 60 * 1000;  //1min
    @RequestMapping("/check")
    public boolean check(String inputCaptcha, HttpSession session) {
//        1.判断输入的验证码是否为空
        if(!StringUtils.hasLength(inputCaptcha)) {
            return false;
        }
//        2.获取生成的验证码
        String captcha = (String) session.getAttribute(KAPTCHA_SESSION_KEY);
        Date saveDate = (Date) session.getAttribute(KAPTCHA_SESSION_DATE);
//        3.判断验证码与获取验证码是否一致
//        4.验证验证码是否过期
        if (inputCaptcha.equalsIgnoreCase(captcha)) {
            if (saveDate != null || System.currentTimeMillis() - saveDate.getTime() < TIME_OUT) {
                return true;
            }
        }
        return false;
    }
}
